package com.lwl.jvm.classloading;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义类加载器
 *
 * @author liwenlong - 2018/5/27 14:19
 */
public class MyClassLoader extends ClassLoader {

    private String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = this.getData(name);
        if (classData != null) {
            //defineClass方法将字节码转化为类
            return defineClass(name, classData, 0, classData.length);
        }
        return super.findClass(name);
    }

    private byte[] getData(String className) {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        String path = classPath + File.separator + className.replace(".", File.separator) + ".class";
        try {
            in = new FileInputStream(path);
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
